<template>
  <!-- 新增公告栏 -->
  <div class="head-announcement" v-if="announcements.length">
    <el-icon class="bell-icon">
      <BellFilled/>
    </el-icon>
    <span class="bell-text">公告：</span>
    <div class="announcement-content">
      {{ currentAnnouncement }}
    </div>
  </div>
  <div class="header-container">
    <div class="left-section">
      <!-- 系统 Logo -->
      <div class="logo-section">
        <img :src="logoImage" alt="系统 Logo" class="system-logo" />
      </div>

      <!-- 导航菜单 -->
      <el-menu mode="horizontal" class="nav-menu">
        <el-menu-item index="/client/home">
          <router-link to="/client/home" class="nav-link">首页</router-link>
        </el-menu-item>
        <el-menu-item index="/client/activityList">
          <router-link to="/client/activityList" class="nav-link">公益活动</router-link>
        </el-menu-item>
        <el-menu-item index="/client/serviceList">
          <router-link to="/client/serviceList" class="nav-link">养老服务</router-link>
        </el-menu-item>
        <el-menu-item index="/client/nursingList">
          <router-link to="/client/nursingList" class="nav-link">养老院信息</router-link>
        </el-menu-item>
        <el-menu-item index="/client/chat">
          <router-link to="/client/chat" class="nav-link">AI智能对话</router-link>
        </el-menu-item>
        <el-menu-item index="/client/videoStudy">
          <router-link to="/client/videoStudy" class="nav-link">视频学习</router-link>
        </el-menu-item>
      </el-menu>
    </div>

    <div class="right-section">
      <!-- 右侧用户信息和下拉菜单 -->
      <div class="user-profile"
           @click.stop="toggleDropdown"
           @mouseenter="showDropdown = true"
           @mouseleave="showDropdown = false">
        <!-- 用户头像 -->
        <img
            :src="userAvatar"
            class="user-avatar"
            alt="用户头像"
            @error="handleImageError"
        />

        <!-- 下拉菜单 -->
        <transition name="dropdown-transition">
          <div v-show="showDropdown"
               class="dropdown-menu"
               :class="{ 'dropdown-up': needPositionUp }">
            <!-- <div class="user-info-item">
              <span class="info-label">账号：</span>
              {{ userAccount }}
            </div> -->
            <div class="user-info-item">
               <router-link to="/userInfo/editMessage" class="link">
               <span>用户信息编辑</span>
               </router-link>
            </div>
            <div class="user-info-item">
              <router-link to="/register/Activity" class="link">
                <span>我报名的活动</span>
               </router-link>
            </div>
            <div class="user-info-item">
              <router-link to="/appo/Service" class="link">
                <span>我预约的服务</span>
               </router-link>
            </div>

            <div class="user-info-item">
              <router-link to="/manager/Elderly" class="link">
                <span>我绑定的老人信息</span>
              </router-link>
            </div>
           
            <el-divider class="info-divider"/>
            <div class="logout-item" @click="handleLogout">
              <el-icon class="logout-icon">
                <SwitchButton/>
              </el-icon>
              退出登录
            </div>
          </div>
        </transition>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onBeforeUnmount, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import {SwitchButton, BellFilled} from '@element-plus/icons-vue';
import { useStore } from 'vuex';
import { getLoginerInfo, logout } from '../service/userApi';
import defaultAvatar from '../assets/images/default.jpeg';
import { getHomePageList } from '../service/announcementApi'; // 请确保路径正确
import logoImage from '@/assets/images/logo1.png'
// 公告相关逻辑
const announcements = ref([]);
const currentIndex = ref(0);
let timer = null;
const router = useRouter();
const route = useRoute();
const store = useStore();

// 响应式状态
const state = reactive({
  userInfo: null,
  dropdownPositionUp: false
});

const showDropdown = ref(false);
const lastScrollPosition = ref(0);

// 计算属性
const userAccount = computed(() => state.userInfo?.loginUserName || '未登录');
const userName = computed(() => state.userInfo?.realName || '游客');
const userAvatar = computed(() => state.userInfo?.headUrl || defaultAvatar);
const pageTitle = computed(() => route.meta.title || '管理平台');
const showBackButton = computed(() => router.options.history.state.back !== null);

// 自动检测下拉菜单位置
const needPositionUp = computed(() => {
  const viewportHeight = window.innerHeight;
  const avatarBottom = document.querySelector('.user-profile')?.getBoundingClientRect().bottom || 0;
  return avatarBottom > viewportHeight * 0.7;
});

// 获取公告数据
const fetchAnnouncements = async () => {
  try {
    const res = await getHomePageList();
    announcements.value = res.data.map(item => item.title); // 提取标题
    startCarousel();
  } catch (error) {
    console.error('获取公告失败:', error);
    ElMessage.error('公告加载失败');
  }
};

// 启动轮播
const startCarousel = () => {
  if (announcements.value.length > 1) {
    timer = setInterval(() => {
      currentIndex.value = (currentIndex.value + 1) % announcements.value.length;
    }, 4000); // 4秒切换一次
  }
};

// 当前显示的公告
const currentAnnouncement = computed(() => {
  return announcements.value[currentIndex.value];
});

// 全局点击监听
const handleClickOutside = (event) => {
  if (!event.target.closest('.user-profile')) {
    showDropdown.value = false;
  }
};

onMounted(() => {
  if (store.getters.isAuthenticated) {
    fetchUserInfo();
    fetchAnnouncements();
  }
  document.addEventListener('click', handleClickOutside);
  window.addEventListener('scroll', handleScroll);
});

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside);
  window.removeEventListener('scroll', handleScroll);
});

// 滚动处理优化
const handleScroll = () => {
  const currentPosition = window.scrollY;
  if (Math.abs(currentPosition - lastScrollPosition.value) > 50) {
    showDropdown.value = false;
  }
  lastScrollPosition.value = currentPosition;
};

// 图片加载失败处理
const handleImageError = (e) => {
  e.target.src = defaultAvatar;
};

// 用户信息获取逻辑
const fetchUserInfo = async () => {
  const response = await getLoginerInfo();
  state.userInfo = {
    loginUserName: response.data.username,
    realName: response.data.name,
    headUrl: response.data.avatar || defaultAvatar
  };
};

// 退出登录
const handleLogout = async () => {
  await logout();
  await store.dispatch('logout');
  await router.replace({ path: '/login', query: { redirect: route.fullPath } });
  ElMessage.success('已安全退出');
};

// 下拉菜单切换逻辑
const toggleDropdown = () => {
  showDropdown.value = !showDropdown.value;
};
</script>

<style scoped>
.header-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  background: #ffffff;
  border-bottom: 1px solid #ebeef5;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.left-section {
  display: flex;
  align-items: center;
  gap: 24px;
}

.logo-section {
  display: flex;
  align-items: center;
}

.system-logo {
  margin-right: 46px;
  height: 64px;
}

.nav-menu {
  display: flex;
  gap: 24px;
  font-size: 16px;
  color: #333333;
}

.nav-link {
  text-decoration: none;
  color: #333333;
}

.nav-link:hover {
  color: #409eff;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 24px;
}

.user-profile {
  position: relative;
  cursor: pointer;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 2px solid #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}
.head-announcement {
  background: linear-gradient(180deg, #a5d8aa,#80e58b) !important;
  padding: 2px 20px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ebeef5;
}
.bell-icon {
  color: #1F3A5F;
  margin-right: 8px;
  font-size: 18px;
}

.bell-text {
  color: #1F3A5F;
  font-weight: 500;
  font-size: 14px;
  margin-right: 10px;
}
.announcement-content {
  color: #606266;
  flex: 1;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  font-size: 14px; /* 调整为你需要的文字大小 */
  animation: fadeIn 1s;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}
.user-avatar:hover {
  transform: scale(1.08);
}

.dropdown-menu {
  position: absolute;
  right: 0;
  top: 48px;
  width: 200px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  z-index: 9999;
  padding: 12px 0;
}

.dropdown-menu.dropdown-up {
  bottom: 100%;
  top: auto;
  margin-bottom: 8px;
}

.user-info-item {
  padding: 8px 20px;
  font-size: 14px;
  color: #606266;
  display: flex;
  align-items: center;
  transition: background-color 0.3s;
}

.user-info-item:hover {
  background-color: #f5f7fa;
}

.info-label {
  color: #909399;
  min-width: 60px;
  display: inline-block;
}

.info-divider {
  margin: 8px 0;
  border-color: #ebeef5;
}

.logout-item {
  padding: 8px 16px;
  color: #f56c6c;
  display: flex;
  align-items: center;
  transition: background-color 0.3s;
}

.logout-item:hover {
  background-color: #fef0f0;
}

.logout-icon {
  margin-right: 8px;
  font-size: 16px;
}

/* 下拉动画 */
.dropdown-transition-enter-active {
  animation: dropdown-in 0.25s ease-out;
}

.dropdown-transition-leave-active {
  animation: dropdown-out 0.2s ease-in;
}

@keyframes dropdown-in {
  0% {
    opacity: 0;
    transform: translateY(-10px);
  }
  100% {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes dropdown-out {
  0% {
    opacity: 1;
    transform: translateY(0);
  }
  100% {
    opacity: 0;
    transform: translateY(-10px);
  }
}
</style>